import React, { memo, useEffect, useState } from "react";
import { connect } from "react-redux";
import { Navigate } from "react-router-dom";
import { Button, Toast } from "antd-mobile";
import NavBarAgain from "./../../components/NavBarAgain";
import { getPhoneCode, login, getUserInfo } from "./../../service/api";
import { Form, Input, Button } from "antd-mobile";
import action from "./../../store/actions/index";
import "./index.less";

const Login = (props) => {
  const { navigate, setUserInfo, sup } = props;

  if (window.localStorage.getItem("tk")) {
    return <Navigate to="/" replace />;
  }

  /* 定义状态 */
  let [formInstance] = Form.useForm();
  let [btnDisabled, setBtnDisabled] = useState(false);
  let [submitLoading, setSubmitLoading] = useState(false);
  let [codeBtnLoading, setCodeBtnLoading] = useState(false);
  let [countdownText, setCountdownText] = useState("发送验证码");

  /* 倒计时 */
  let timer = null;
  let countTime = 10;
  const setCountdown = () => {
    countTime--;
    if (countTime <= 0 || countTime === 10) {
      clearInterval(timer);
      setCountdownText("发送验证码");
      setBtnDisabled(false);
      return;
    }
    setCountdownText(`${countTime}秒后重新获取验证码`);
  };

  /* 获取验证码 */
  const onSend = async () => {
    try {
      let { phone } = await formInstance.validateFields(["phone"]);
      setCodeBtnLoading(true);
      let result = await getPhoneCode(phone);
      if (result?.code === 0) {
        if (!timer) timer = setInterval(setCountdown, 1000);
        setCountdown();
      } else {
        Toast.show({
          icon: "fail",
          content: "获取验证码失败，请稍后重试",
        });
      }
      setCodeBtnLoading(false);
      setBtnDisabled(true);
    } catch (error) {
      console.log(error);
    }
  };

  /* 表单校验成功，调登录接口 */
  const onFinish = async (values) => {
    try {
      let { phone, code } = values;
      setSubmitLoading(true);
      let { code: CodeHttp, token } = await login(phone, code);
      debugger;
      if (CodeHttp === 0) {
        Toast.show({
          icon: "success",
          content: "登录成功",
        });
        localStorage.setItem("tk", token);
        getLoginUserInfo();
      } else {
        Toast.show({
          icon: "fail",
          content: "登录失败",
        });
      }
      setSubmitLoading(false);
    } catch (error) {
      console.log("请求登录接口失败 ...", error);
    }
  };

  /* 登录成功，获取用户信息 ，存储到redux里面 */
  const getLoginUserInfo = async () => {
    const { code, data } = await getUserInfo();
    if (code === 0) {
      window.localStorage.setItem("useInfo", JSON.stringify(data));
      setUserInfo(data);
      const to = sup.get("to");
      // 如果跳进来URL带to参数，则跳转到to的路径，替换模式。 否则原理返回
      to ? navigate(`/${to}`, { replace: true }) : navigate(-1);
    }
  };

  /* 组件卸载清除定时器,也就是离开当前组件时候触发！！！ */
  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
    };
  }, []);

  return (
    <>
      <NavBarAgain></NavBarAgain>
      <div className="login-page">
        <h2>登录/注册</h2>
        <Form
          layout="horizontal"
          style={{ "--border-top": "none" }}
          onFinish={onFinish}
          form={formInstance}
          footer={
            <Button
              block
              type="submit"
              color="primary"
              size="large"
              loading={submitLoading}
            >
              登录
            </Button>
          }
        >
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: "手机号不能为空" },
              { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确" },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            label="短信验证码"
            extra={
              <Button
                color="primary"
                onClick={onSend}
                loading={codeBtnLoading}
                disabled={btnDisabled}
              >
                {countdownText}
              </Button>
            }
            rules={[{ required: true, message: "验证码不能为空" }]}
          >
            <Input placeholder="请输入短信验证码" />
          </Form.Item>
        </Form>
      </div>
    </>
  );
};

export default connect(null, action.baseAction)(Login);

/**
 *
 * 前端手机号校验规则作用：
 *  @1 减少HTTP请求
 * @2 防止SQL注入
 */
